from datetime import datetime, time

from flask import Flask, request, render_template, jsonify, flash, redirect, url_for, g, session
from sqlalchemy.sql.functions import current_user
import config
from exts import db
from bluePrints.admin import admin
from bluePrints.user import user
from bluePrints.book import book
from forms import NewStoreForm, BorrowForm, SearchStudentForm, StoreForm, ChangePasswordForm
from models import UserModel, AdminModel
from flask_migrate import Migrate
from forms import Login

app = Flask(__name__)
# 绑定配置文件
app.config.from_object(config)

db.init_app(app)

migrate = Migrate(app, db)

app.register_blueprint(admin)
app.register_blueprint(user)
app.register_blueprint(book)


@app.route('/')
def hello_world():  # put application's code here
    form = Login()
    return render_template("login.html", form=form)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        form = Login()
        return render_template('login.html', form=form)
    elif request.method == 'POST':
        form = Login()
        if form.validate_on_submit():
            account = UserModel.query.filter_by(account_number=form.account.data, password=form.password.data).first()
            if account is None:
                account = AdminModel.query.filter_by(account_number=form.account.data,
                                                     password=form.password.data).first()
                if account is None:
                    flash(u'用户名或密码错误！')
                    return redirect(url_for('login'))
                else:
                    session['account_id'] = account.account_number
                    return redirect(url_for('user.index'))
            else:
                session['account_id'] = account.account_number
                return redirect(url_for('user.index'))


@app.route('/logout')
def logout():
    session.clear()
    return redirect('/')


@app.before_request
def before_login():
    account_id = session.get('account_id')
    if account_id:
        account = UserModel.query.filter_by(account_number=account_id).first()
        if account is None:
            account = AdminModel.query.filter_by(account_number=account_id).first()
        setattr(g, 'account', account)
    else:
        setattr(g, 'account', None)


@app.context_processor
def user_info():
    return {'account': g.account}


if __name__ == '__main__':
    app.run()
